package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.MenuDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Menu;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * 检查项服务
 */

@Service(interfaceClass = MenuService.class)
@Transactional
public class MenuServiceImpl implements MenuService {

    @Autowired
    private MenuDao menuDao;

    //分页查询
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();//ThreadLocal
        PageHelper.startPage(currentPage,pageSize);//分页插件，会在执行sql之前将分页关键字追加到SQL后面
        //查找所有的父ID
        Page<Menu> page = menuDao.findByCondition(queryString);
        List<Menu> rows=page.getResult();
       for (Menu row : rows) {
            //获取父ID
            Integer id = row.getId();
            //获取父ID为这个的所有子集合
            List<Menu> list=menuDao.findParentIdMenu(id);
            row.setChildren(list);
            System.out.println(row.getChildren().size());
        }
        return new PageResult(page.getTotal(),rows);
    }

    @Override
    public void add(Menu menu) {
        if (menu.getParentMenuId()!=null){
           menu.setLevel(2);
        }else {
            menu.setLevel(1);
        }

        //查找父ID的path 在统计父ID的子菜单
        long count=menuDao.count(menu.getParentMenuId());
        //最后插入path
        String path=menuDao.findPath(menu.getParentMenuId());
        menu.setPath("/"+path+"-"+(count+1));
        menuDao.add(menu);
    }

    @Override
    public List<Menu> findparentMenuIds() {
        List<Menu> menus=menuDao.findparentMenuIds();
        return menus;
    }

    @Override
    public Menu findById(Integer id) {
       return menuDao.findById(id);
    }

    @Override
    public void update(Menu menu) {
        if (menu.getParentMenuId()!=null){
            menu.setLevel(2);
        }else {
            menu.setLevel(1);
        }
        //查找父ID的path 在统计父ID的子菜单
        long count=menuDao.count(menu.getParentMenuId());
        //最后插入path
        String path=menuDao.findPath(menu.getParentMenuId());

        //找到数据的父ID
        int ParentId= menuDao.findParentId(menu.getId());
        //如果传入的父ID没变的话
        if (ParentId==menu.getParentMenuId()){
            menu.setPath("/"+path+"-"+count);
        }else {
        menu.setPath("/"+path+"-"+(count+1));
        }
        menuDao.update(menu);
    }

    @Override
    public void delete(Integer id) {
        menuDao.delete(id);
    }

}